import { reqAddHospitalSet, reqGetIdHospitalSet, reqUpdateHospitalSet } from '@/api/hospital/hospitalSet';
import { Card, Form, Input, Button, Space, message } from 'antd';
import React, { useEffect } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';

function AddOrUpdateHospitalSet() {
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const location = useLocation();
  // 拿到传递过来的id
  const id = location.state as number;

  useEffect(() => {
    // 如果是编辑页面就数据回显
    if (id) fetch();
  }, []);

  // 数据回显
  async function fetch() {
    const res = await reqGetIdHospitalSet(id);
    // 把数据添加到表单里面去
    form.setFieldsValue(res);
  }

  // 提交表单
  const addOrUpdate = async (values: any) => {
    // 判断是编辑还是添加
    if (id) {
      // 编辑
      // 给表单数据添加id
      values.id = id;
      try {
        await reqUpdateHospitalSet(values);
        // 编辑成功提示
        message.success('编辑成功');
        navigate(-1);
      } catch (error) {
        console.log(error);
        message.error('编辑失败');
      }
    } else {
      // 添加
      // 发请求添加数据，跳转回去
      try {
        await reqAddHospitalSet(values);
        // 添加成功提示
        message.success('添加成功');
        navigate(-1);
      } catch (error) {
        console.log(error);

        message.error('添加失败');
      }
    }
  };

  return (
    <>
      <Card>
        <Form onFinish={addOrUpdate} form={form} labelCol={{ span: 3 }} wrapperCol={{ span: 21 }}>
          <Form.Item label="医院名称" name="hosname" rules={[{ required: true, message: '请输入医院名称' }]}>
            <Input placeholder="医院名称"></Input>
          </Form.Item>
          <Form.Item label="医院编码" name="hoscode" rules={[{ required: true, message: '请输入医院编码' }]}>
            <Input placeholder="医院编码"></Input>
          </Form.Item>
          <Form.Item label="api基础路径" name="apiUrl" rules={[{ required: true, message: '请输入api基础路径' }]}>
            <Input placeholder="api基础路径"></Input>
          </Form.Item>
          <Form.Item label="联系人姓名" name="contactsName" rules={[{ required: true, message: '请输入联系人姓名' }]}>
            <Input placeholder="联系人姓名"></Input>
          </Form.Item>
          <Form.Item
            label="联系人手机号"
            name="contactsPhone"
            rules={[{ required: true, message: '联系人电话是必填且11位的的', pattern: /^1[3-9]\d{9}$/ }]}>
            <Input placeholder="联系人手机号"></Input>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 3 }}>
            <Space>
              <Button type="primary" htmlType="submit">
                保存
              </Button>
              <Button
                onClick={() => {
                  navigate(-1);
                }}>
                返回
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </>
  );
}

export default AddOrUpdateHospitalSet;
